package Test3;

import java.util.concurrent.locks.ReentrantLock;
//实现Runnable接口完成需求
public class SaleTicketRunnable implements Runnable{
    //创建票数属性
    private int Tickets;
    //创建Lock对象
    private ReentrantLock lock = new ReentrantLock();
    //构造方法
    public SaleTicketRunnable(){
    }
    public SaleTicketRunnable(int Tickets) {
        this.Tickets = Tickets;
    }
    public int getTickets() {
        return Tickets;
    }
    public void setTickets(int Tickets) {
        this.Tickets = Tickets;
    }
    //重写run方法
    @Override
    public void run() {
        lock.lock();//开始加锁
        int sale = getTickets();//获取票数
        //开始循环卖票
        while (sale >0){
            System.out.println("正在买票，请稍后...");
            sale -= 1;//票数减一
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("取票完成！还剩"+sale+"张票");
        }
        setTickets(sale);//结果保存
        lock.unlock();//释放锁
    }

    public static void main(String[] args) {
        //创建对象
        SaleTicketRunnable saleTicketRunnable = new SaleTicketRunnable(100);
        //创建三个线程
        Thread t1 = new Thread(saleTicketRunnable);
        Thread t2 = new Thread(saleTicketRunnable);
        Thread t3 = new Thread(saleTicketRunnable);
        System.out.println("开始售票...");
        //启动三个线程
        t1.start();
        t2.start();
        t3.start();
    }


}
